package com.rainsoftware.LicenseSystem.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtUtil {
    private static final String SECRET_KEY = "4d0c83caea8cbf5376ef97207010a6b043bf456340b996cdb43bc3394814956240b80f4df3f25e85b27cbece8795ff6bbebb82fb679dc60ee0e26bd8b16b696447686c5b202a8e9a3dc3863d51b0b7b755a1d3fb4386c8685f247e18a0611166c77d2a06bff125ebafa97c430d90f59f40ec304326d2b0cb1959117eb64a6ba41a8a0f940f16e0c9d28e0b5ab54bc6d1fcbbbf11b2bdec9f686c9f23685e34a97bd9c85fdf648e64f4164cf3aeec49399f661fb278316d6134033b7569b843562c3ad7b5d9cb0b47a479b62653039ea6c06be10c21b545b6183dabfed5bf8c9b95403ea6810d8e85fcc40cedf3fc9118cc65da43b0925c3c8a8658dfeb8afcab";
    private static final long EXPIRATION_TIME = 30000 * 60 * 60; // 30 hour

    private static final Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());

    public static String generateToken(String username, int userId, String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId); // Store userId in the token
        claims.put("role", role);     // Store role in the token

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username) // The username is still stored as subject
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) // Token expires in 10 hours
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public static int extractUserId(String token) {
        return extractClaim(token, claims -> claims.get("userId", Integer.class));
    }

    public static String extractUserRole(String token) {
        return extractClaim(token, claims -> claims.get("role", String.class));
    }

    public static <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private static Claims extractAllClaims(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    public static boolean isTokenValid(String token, String username) {
        return (extractUsername(token).equals(username) && !isTokenExpired(token));
    }

    private static boolean isTokenExpired(String token) {
        return extractClaim(token, Claims::getExpiration).before(new Date());
    }
}
